<template>
    <el-row class="user-info-form" type="flex" justify="center">
        <el-col>
            <el-form label-position="top" :model="editForm" :rules="editFormRules" ref="editForm" @submit.native.prevent>
                <input type="hidden"  v-model="editForm.id">
                <el-form-item label="图片：">
                  <el-upload
                      :action="QINIUUPLOADURL"
                      :multiple="true"
                      ref="upload"
                      list-type="picture-card"
                      :data="qiniuData"
                      :on-success="handleAvatarSuccess"
                      :on-remove="handleRemovePic"
                      :on-error="handleError"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="$imgPreview"
                      :file-list="qiniuData.fileList" 
                      :limit="1"
                      :on-exceed="handleExceed"
                      accept="image/gif,image/jpeg,image/jpg,image/bmp,image/png">
                      <div slot="tip" class="el-upload__tip">请上传小于2M的图片</div>
                      <i class="el-icon-plus"></i>
                  </el-upload>
                </el-form-item>
                <el-form-item label="名称：" prop="name">
                    <el-input v-model.trim="editForm.name" auto-complete="off" placeholder="名称不能重复"></el-input>
                </el-form-item>
                <el-form-item label="消防系统：" prop="fireSystem">
                  <el-select filterable v-model="editForm.fireSystem" placeholder="选择消防系统">
                    <el-option
                        v-for="item in roleOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注：">
                    <el-input type="textarea" v-model="editForm.remarks"></el-input>
                  </el-form-item>
                <el-form-item label-width="0" class="verifyidentity-button">
                    <el-button round @click="closeDialog()">取消</el-button>
                    <el-button type="primary" round @click="saveEdit('editForm')">确定</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script>
import util from '@/utils/util'
import { qnToken} from '@/api/api'
import {updateAc} from '@/api/assets'

export default {
  name:'AssetClassLibForm',
  props: {
    editInfo: {
        type: Object,
        required: false
    },
    closeDialog: {
        type: Function,
        required: true
    },
  },
  data() {
    return {
        qiniuData:{//上传图片携带的参数
            token : "",
            key : "",
            fileList:[],
        },
        defaultImg: this.GLOBAL.defaultImg,
        util:util,
        roleOptions: [],
        unRelateVideoTotal: 0,
        editForm: {
            id: 0,
            organizationId:0,
            name:'',
            fireSystem:'',
            assetCategoryPicUrl:'',
            remarks:''
        }, 
        editFormRules: {
            name: [
                { required: true, message: '请输入名称', trigger: 'blur' },
            ],
            fireSystem: [
              { required: true, message: '请选择消防系统', trigger: 'change' }
            ],
        },
    }
  },
  created() {
      let that = this
      this.getToken();//获取token
      //绑定下拉框
      util.ilinkArrHandle.delDicArr_keyVal(55, function(arr){
        that.roleOptions.push.apply(that.roleOptions, arr);
      })
      let infoObj = this.editInfo
      if(infoObj.id) {//编辑
          this.editForm.id = infoObj.id
          this.editForm.organizationId = infoObj.organizationId||0
          this.editForm.name = infoObj.name
          this.editForm.fireSystem = infoObj.fireSystem
          this.editForm.remarks = infoObj.remarks
          this.editForm.assetCategoryPicUrl = infoObj.assetCategoryPicUrl
          infoObj.assetCategoryPicUrl?$.each(infoObj.assetCategoryPicUrl.split(','),(index,url)=>{
            this.qiniuData.fileList.push({
                name:'图片'+index,
                url:url
            })
          }):''
      }
  },
  methods: {
    getToken(){  //上传之前获取 token
      qnToken({}).then((result) => {
        this.qiniuData.token= result.data
      })
    },
    beforeAvatarUpload: function(file){//重命名和校验
      var fielLocal = file.name.split(".")
      var fielType = "." + fielLocal[fielLocal.length-1]
      var fielLocalName = fielLocal[0]
      this.qiniuData.key = 'ilink_'+new Date().getTime()+fielType   
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isJPG && !isPNG) {
        this.$message.error("图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt20M) {
        this.$message.error("图片大小不能超过 20MB!");
        return false;
      }
    },
    handleAvatarSuccess: function(res, file, fileList) {//上传成功
        this.qiniuData.fileList = fileList;
    },
    handleRemovePic: function(file, fileList) {//删除成功
        this.qiniuData.fileList = fileList;
    },
    handleError: function(res) {
        this.$message({
          message: "上传失败",
          duration: 2000,
          type: "warning"
        });
    },
    handleExceed(files, fileList) {//文件超出个数限制时的钩子
      this.$message.warning(`只能上传一张图片！`);
    },
    saveEdit(formName) {
        // 阻止事件冒泡
        event.stopPropagation()
        let that = this
        that.$refs[formName].validate((valid) => {
          if (valid) {
            let parames = that.editForm
            parames.assetCategoryPicUrl= util.ilinkArrHandle.getqiniuPicUrlArr(that.qiniuData.fileList).toString()
            updateAc(parames).then(res => {
              if( res.status === 200) {
                that.$message({
                  type: 'success',
                  message: '保存成功！!'
                })
                that.closeDialog(true)
              }else{
                that.$message.error(res.info)
              }
            });
          } else {
              return false
          }
        });
    },
  }
}
</script>
